package team.lourd.network.system.audit;

import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component("auditorAware")
public class UserAuditorAware implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        if (ctx == null) {
            return Optional.of("null");
        }
        if (ctx.getAuthentication() == null) {
            return Optional.of("null");
        }
        if (ctx.getAuthentication().getPrincipal() == null) {
            return Optional.of("null");
        }
        // 一般是获取用户名
        Authentication authentication = ctx.getAuthentication();
        System.out.println(authentication.getPrincipal());
        return Optional.of(authentication.getPrincipal().toString());
    }
}
